package com.qc31.comlib.choose.car

import com.qc31.baselib.utils.CacheMMKV
import com.qc31.comlib.entity.CarLick
import com.qc31.comlib.entity.HistoryCars
import io.reactivex.rxjava3.subjects.BehaviorSubject

/** @Author Jasper @Time 2020/7/24 @Desc */
object ChooseCars {
    var isVideo = false
    private val historyEntity by lazy {
        CacheMMKV.decodeParcelable("history_car", HistoryCars::class.java)
            ?: HistoryCars()
    }

    val listObservable: BehaviorSubject<MutableList<HistoryCars.ListBean>> by lazy {
        BehaviorSubject.create<MutableList<HistoryCars.ListBean>>()
    }


    fun initData() {
        val entityts = ArrayList<HistoryCars.ListBean>()
        if (isVideo) {
            entityts.clear()
            for (entity in historyEntity.list) {
                if (entity.isVideo) entityts.add(entity)
            }
            listObservable.onNext(entityts)
        } else {
            listObservable.onNext(historyEntity.list)
        }
    }

    fun addCars(
        carId: String, carName: String,
        carPlate: String, iconLink: String,
        videos: String?, isVideo: Boolean
    ) {
        for (entity in historyEntity.list) {
            if (carId == entity.carId) {
                historyEntity.list.remove(entity)
                break
            }
        }
        historyEntity.list.add(
            0,
            HistoryCars.ListBean(
                carId,
                carName,
                carPlate,
                iconLink,
                videos,
                isVideo
            )
        )
        if (historyEntity.list.size > 40) historyEntity.list.removeLast()
        CacheMMKV.encodeParcelable("history_car", historyEntity)
    }


    fun getLickCars(): MutableList<CarLick> {
        val map = historyEntity.list.map {
            CarLick(it.carId, it.carName, it.carPlate, it.iconLink, it.videos)
        }.toMutableList()

        return map
    }

    fun clearChooseCar() {
        historyEntity.list.clear()
    }

}